package com.ruoyi.app.util;
import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;

public class AESUtil {

    private static final String FIXED_SALT = "yQoi8fiN9EHvHTiaHRdI5A=="; // 你的固定盐值

    /**
     * 生成用户 AES 密钥
     * @param userId    用户 ID
     */
    public static String generate32BitKey(long userId) {
        try {
            // 获取 SHA - 256 哈希算法实例
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            // 将用户 ID 转换为字节数组
            byte[] inputBytes = String.valueOf(userId).getBytes();
            // 计算哈希值
            byte[] hashBytes = md.digest(inputBytes);

            StringBuilder sb = new StringBuilder();
            for (byte b : hashBytes) {
                // 将字节转换为两位的十六进制字符串
                sb.append(String.format("%02x", b));
            }
            // 截取前 32 位
            return sb.toString().substring(0, 32);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * AES 加密（自动生成随机 IV）
     */
    public static String encryptAES(String data, String key) throws Exception {
        SecretKeySpec secretKeySpec = new SecretKeySpec(Base64.getDecoder().decode(key), "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

        // 生成随机 IV
        //byte[] iv = generateIV();
        byte[] iv = new byte[16];
        IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);

        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
        byte[] encrypted = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));

        // 拼接 IV 和加密数据
        byte[] combined = new byte[iv.length + encrypted.length];
        System.arraycopy(iv, 0, combined, 0, iv.length);
        System.arraycopy(encrypted, 0, combined, iv.length, encrypted.length);

        return Base64.getEncoder().encodeToString(combined);
    }

    public static String decryptAES(String encryptedData, String key,String ivStr) throws Exception {
        // 1. Base64 解码密文
        byte[] decodedData = Base64.getDecoder().decode(encryptedData);

        // 2. Base64 解码密钥，确保长度为 32 字节（AES-256）
        //byte[] keyBytes = Base64.getDecoder().decode(base64Key);
        byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8);
        if (keyBytes.length != 32) {
            throw new IllegalArgumentException("AES-256 密钥必须是 32 字节！");
        }
        SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES");

        // 3. 设定固定 IV（确保和前端一致）L+cNwKUN6hd1YeOm
        byte[] iv = ivStr.getBytes(StandardCharsets.UTF_8);
        IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);

        // 4. 配置 AES-CBC-PKCS5Padding 模式
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);

        // 5. 进行解密
        byte[] original = cipher.doFinal(decodedData);

        // 6. 返回明文字符串
        return new String(original, StandardCharsets.UTF_8);
    }

    public static void main(String[] args) throws Exception {
        Long orderId = Long.parseLong("00");
        System.out.println("---------------orderId:"+orderId);
        long timestamp = System.currentTimeMillis() / 60000; // 生成秒级时间戳
        String aesKey = generate32BitKey(196981414623714304L);
        System.out.println("------aesKey:"+aesKey);
        String decryptedAmountStr = AESUtil.decryptAES("zhu4IeySALAUo/efbRAva5Jib5DTNFSB9bxM+EGH5D8=", "cb687yjajQ2JJviYRy6eIoterWQHF7mW","");
        System.out.println("------decryptedAmountStr:"+decryptedAmountStr);
    }

}


